/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package post.dataaccess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import post.Payment;
import post.ProductSpec;
import post.Store;
import post.Transaction;
import post.TransactionItem;

/**
 *
 * @author Harry
 */
public class TransactionReader {

    private Store store;
    private String transactionFile;
    private String[] wholeTransactions;
    private int numTransactions=0;
    private static int position;
    
    public TransactionReader(Store store, String transactionFile) throws IOException {
        this.store = store;
        this.transactionFile = transactionFile;
        wholeTransactions = new String[100];
        try {
            this.transactionFile=transactionFile;
            FileReader fr = new FileReader(transactionFile);
            /*location of products.txt file will be passed as the arguement, pls change the location accordingly.*/
            
            BufferedReader br = new BufferedReader(fr);
            boolean flag = true;        
            int i=0;
            String temp=new String();
            while(true)
                {
                    String s = br.readLine();   //Reads the file line by line                    
                    if(s==null)                 //comparison to determine end of file (null)
                    {  
                        break;                    
                    }
                    if (s.equals("###############################################################################################"))
                    {
                        wholeTransactions[i++]=temp;
                     //   System.out.println(temp);
                        temp="";                                
                    }                  
                    else 
                    {                        
                        temp+=s;
                    }
               }
            numTransactions=i;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ProductReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    
    
    public boolean hasMoreTransaction() {

        if (position<numTransactions)
            return true;
        else
            return false;
    }

    public String getNextTransaction() {

        return wholeTransactions[position++];
    }

    public String[] loadAll() {

        return wholeTransactions;
    }

    public void addTransaction(Transaction transaction,ProductReader productcatalog) throws IOException {
        String newTransaction=new String();       
        newTransaction=store.getName()+"\t"+store.getAddress()+"\n";
        newTransaction+="Customer Name : "+transaction.getCustomerName()+"\t"+"Time of Transaction : "+transaction.getDate()+"\n";
        newTransaction+="----------------------------------------------------------------------------- \n";
        TransactionItem[] itemList=transaction.getTransactionItem();
        
        newTransaction+="Prooduct UPC \t Quantity \t Unit Price Sub-Total\n";
        float total=0;
        for (int i=0;i<transaction.getNumTransItems();i++){
            newTransaction+= itemList[i].getUpc()+" \t "+itemList[i].getQuantity()+" \t $"+productcatalog.getPriceByUPC(itemList[i].getUpc())+" \t\t $"+Float.toString(productcatalog.getPriceByUPC(itemList[i].getUpc())*+itemList[i].getQuantity())+"\n";
            total+=productcatalog.getPriceByUPC(itemList[i].getUpc())*+itemList[i].getQuantity();
        }        
        newTransaction+="----------------------------------------------------------------------------- \n";
        newTransaction+="Total : $"+total+"\n";
        newTransaction+="Paid By : "+transaction.getPaymentMode().toString();
        String payTypeInfo=new String();
        if (transaction.getPaymentMode()==Payment.Cash)
            payTypeInfo="\nAmount Tendered: $" + transaction.getPaymentReceived() +"Balance : "+(transaction.getPaymentReceived()-total);
        if (transaction.getPaymentMode()==Payment.CreditCard)
            payTypeInfo="\nCard Number : "+transaction.getCardNum();
        newTransaction+=payTypeInfo+"\n";
        newTransaction+="###############################################################################################\n";
        
        FileWriter fw = new FileWriter(transactionFile,true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(newTransaction);
        bw.close();
    }
    
    public String[] getTransactionByDate(Date transDate) throws ParseException{       
       String[] result=new String[100];
       int j=0;    
       for (int i=0;i<numTransactions;i++)
        {
            int tempIndex=wholeTransactions[i].indexOf("Time of Transaction : ");
            int endIndex=wholeTransactions[i].indexOf("----",tempIndex);
            String date=wholeTransactions[i].substring(tempIndex+22,endIndex );            
            SimpleDateFormat ft=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
            Date logDate=ft.parse(date);
            SimpleDateFormat ft2=new SimpleDateFormat("MM/dd/yyyy");            
                        
            if (ft2.format(logDate).equals(ft2.format(transDate)))
            {
                result[j++]=wholeTransactions[i];               
            }
        }
        if (j!=0){
            return result;
        }
        else{
        return new String[]{"No transactions for Date : "+transDate.toString()};
        
        }
        
    }
    
    public String[] getTransactionByCustomerName(String customerName){
        String[] result=new String[100];
        int j=0;
        for (int i=0;i<numTransactions;i++)
        {
            //System.out.println(wholeTransactions[i]);
            int tempIndex=wholeTransactions[i].indexOf("Customer Name : ");
            int endIndex=wholeTransactions[i].indexOf("Time",tempIndex);
            String name=wholeTransactions[i].substring(tempIndex+16,endIndex );
            name=name.replaceAll("\t","");
            //System.out.println("#"+name+"#");
            if (name.equals(customerName))
            {                
                result[j++]=wholeTransactions[i];
//                System.out.println(result[j-1]);
            }
        }
        if (j!=0){
            return result;
        }
        else{
            return new String[]{"No sales for name :"+customerName}; 
        }
        }    
}
